package com.customers.filter;

import com.customers.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class Filter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        javax.servlet.Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        javax.servlet.Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI();

        //放行登陆、注册界面
        if(url.contains("userlogin.jsp") || url.contains("userregister.jsp")){
            chain.doFilter(request,response);
            return;
        }

        //放行静态资源
        if(url.contains("/js")||url.contains("css") || url.contains("res")){
            chain.doFilter(request,response);
            return;
        }

        //放行登录、注册操作
        if(url.contains("login") || url.contains("register")){
            chain.doFilter(request,response);
            return;
        }

        //登陆后放行所有界面
        User u1 = (User)request.getSession().getAttribute("registerSeccess");
        User u2 = (User)request.getSession().getAttribute("userSeccess");

        if(u1 != null || u2!=null){
            chain.doFilter(request,response);
            return;
        }

        response.sendRedirect("userlogin.jsp");
    }

}
